#!/usr/bin/env node

const koa = require('koa'),
      bodyparser = require('koa-bodyparser'),
      tasks = require('./routes/tasks.js'),
      user = require('./routes/user.js'),
      json = require('koa-json'),
      logger = require('koa-logger'),
      jwt = require('koa-jwt'),
      jwt2 = require('jsonwebtoken'),
      {JWT_KEY} = require('./lib/constant.js'),
      app = new koa();      
app.use(json());
app.use(logger());
app.use(jwt({secret:JWT_KEY}).unless({path:/\/api\/users\/login$/}));
app.use(bodyparser({enableTypes:['json','form','text']}));
app.use(async(ctx,next)=>{
  let token = ctx.header.authorization;
  if(typeof token !== 'undefined'){
    token = token.split(' ')[1];
    let user = jwt2.verify(token,JWT_KEY);
    ctx.userId = user.id;
  }
  
  await next();
});
app.use(tasks.routes());
app.use(user.routes());
app.listen(8080);
